import api from '@/api'
interface Payparams {
	orderId : string
	payBusinessType : string | number //支付业务类型 1-服务订单支付    2保证金支付
	payType : string | number
	amount : string | number
}

//当前支付成功失败返回对应的true和return false;
//测试前需要手机测试，并且将目录抖音文件夹的json文件复制到抖音开发者工具中
//此金额不可退，设置一分钱测试即可

export const payment = (params : Payparams) => {
	uni.showLoading({
		mask:true,
		title:'支付中'
	})
	let { orderId, payBusinessType, payType } = params
	return new Promise(async (resolve) => {
		const result : any = await api({
			method: 'post',
			url: `/mall/payment/pay/${payBusinessType}/${payType}/?orderId=${orderId}`
		})
		console.log("api接口", result)
		if (result.code != 0) {
			uni.hideLoading()
			resolve(false)
		} else {
			if(Number(params.amount) == 0){
				uni.hideLoading()
				resolve(true)
				return
			}
			//初次
			if(result.data.code==0){
				tt.requestOrder({
					data: result.data.data, // 请勿在前端对data做任何处理
					byteAuthorization: result.data.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
					success: (successresult) => {
						console.log('获取抖音订单号成功', successresult)
						//绑定抖音订单号
						console.log(111111)
						api({
							method: 'get',
							url: `/mall/payment/pay/bindthirdTradeId`,
							data:{
								paymentRecordId:result.data.paymentRecordId,
								thirdTradeId:successresult.orderId
							}
						}).then(res=>{
							console.log(33333,res)
						})
						tt.getOrderPayment({
							success: (suc) => {
								console.log('支付成功回调', suc)
								uni.hideLoading()
								resolve(true)
							},
							fail: (err) => {
								console.log('支付失败回调', err)
								uni.hideLoading()
								resolve(false)
							},
							orderId: successresult.orderId
						})
					},
					fail: (failresult) => {
						console.log('获取抖音订单号失败', failresult)
						uni.hideLoading()
						resolve(false)
					},
				});
			}
			//继续
			if(result.data.code==1){
				tt.getOrderPayment({
					success: (suc) => {
						console.log('支付成功回调', suc)
						uni.hideLoading()
						resolve(true)
					},
					fail: (err) => {
						console.log('支付失败回调', err)
						uni.hideLoading()
						resolve(false)
					},
					orderId: result.data.thirdTradeId
				})
			}
		}
	})
}